from multiprocessing import Process, Pool, Queue
import multiprocessing
import threading
import subprocess
import time

def task():
    start = time.time()
    time.sleep(2)
    end = time.time()
    p = multiprocessing.current_process()
    print('process{0}, run use time={1}'.format(p.name, (end - start)))
    pass


def read_queue(q):
    print('read')
    while True:
        print('get value = {0}'.format(q.get()))


def write_queue(q):
    print('write')
    for i in range(6):
        print('put value = {0}'.format(i))
        q.put('index={0}'.format(i))
        time.sleep(1)


def process_test():
    start = time.time()
    print('main start>>>>>>>')
    # 普通方式， 用时8s
    # for i in range(4):
    #     task()

    # 进程方式， 因为有join操作，用时8s
    # for i in range(4):
    #     process = Process(target=task, name='process{0}'.format(i))
    #     process.start()
    #     process.join()

    # 通过pool创建多进程
    # pool = Pool(2)
    # for i in range(4):
    #     pool.apply_async(func=task)
    # print('main wait...........')
    # pool.close()
    # pool.join()

    # 进程间通信
    # queue = Queue()
    # wp = Process(target=write_queue, args=(queue,))
    # rp = Process(target=read_queue, args=(queue,))
    # wp.start()
    # rp.start()
    # wp.join()
    # rp.terminate()

    # 进程的输入输出
    # r = subprocess.call(['nslookup', 'www.python.org'])
    # print('Exit code:', r)
    #
    # print('$ nslookup')
    # p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
    # print(output.decode('UTF-8'))
    # print('Exit code:', p.returncode)
    print('main end>>>>>>>time={0}'.format((time.time() - start)))


number = 0
lock = threading.Lock()
def caculate():
    global number
    try:
        lock.acquire()
        number = number - 10
        number = number + 10
    finally:
        lock.release()


def repeate():
    for i in range(1000000):
        caculate()


def testlock():
    t1 = threading.Thread(target=repeate)
    t1.start()

    t2 = threading.Thread(target=repeate)
    t2.start()

    t1.join()
    t2.join()

    print('number={0}'.format(number))

local_thread = threading.local()

def thread1():
    if threading.currentThread().name == 'thread1':
        local_thread.one = 2
    print('thread{1}.arg={0}'.format(local_thread.one, threading.currentThread().name))

def processthread():
    local_thread.one = 1
    thread1()

def threadlocaltest():
    # param = {'one': 1}
    local_thread.one = 2
    t1 = threading.Thread(target=processthread, name='thread1')
    t1.start()
    t1.join()

    t2 = threading.Thread(target=processthread, name='thread2')
    t2.start()
    t2.join()


if __name__ == '__main__':
    threadlocaltest()